﻿using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Search.Model;
using System.Data;
using System.Web.SessionState;
using CNKI.TPI.Web.Admin.IBLL;
namespace CNKI.TPI.Web.UI.Controllers.Search
{
    [SessionState(SessionStateBehavior.ReadOnly)]
    public class DetailController : BaseController
    {
        //
        // GET: /Detial/
        int dbID = 0;
        string sysID = "0";
        string dbName = "";
        int mediaType = 0;//类型
        int browsetype = (int)BrowseFromType.CommonBrowse;//浏览来源
        int downtype = (int)DownFromType.CommonDown;//下载来源
        INaviService naviService = null;
        ISearchService searchService = null;
        IFileService fileService = null;
        IUserCenterService centerService = null;
        public DetailController(INaviService naviService, ISearchService searchService, IFileService fileService, IUserCenterService centerService)
        {
            this.naviService = generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.fileService = generator.CreateInterfaceProxyWithTarget<IFileService>(fileService, new IInterceptor[] { new LogInterceptor() });
            this.centerService = generator.CreateInterfaceProxyWithTarget<IUserCenterService>(centerService, new IInterceptor[] { new LogInterceptor() });
        }


        public ActionResult Index()
        {
            SYS_CMS_DATABASE dbinfo = new SYS_CMS_DATABASE();
            if (!String.IsNullOrEmpty(Request.QueryString["dbID"]))
            {
                dbID = int.Parse(Request.QueryString["dbID"]);
            }
            if (!String.IsNullOrEmpty(Request.QueryString["sysID"]))
            {
                sysID = Request.QueryString["sysID"];
            }
            if (!String.IsNullOrEmpty(Request.QueryString["dbName"]))
            {
                dbName = Request.QueryString["dbName"];
                dbinfo = naviService.GetDatabase(dbName);
            }
            if (!String.IsNullOrEmpty(Request.QueryString["type"]))
            {
                mediaType = int.Parse(Request.QueryString["type"]);
            }
            else
            {
                if (dbinfo != null && dbinfo.SysID != 0)
                {
                    mediaType = (int)ResourceHelper.ConvertMediaType(dbinfo.TemplateID);
                }
            }
            if (!String.IsNullOrEmpty(Request.QueryString["Browse"]))
            {
                browsetype = int.Parse(Request.QueryString["Browse"]);
                downtype = (int)DownFromType.AuditDown;
            }
            ViewBag.DownType = downtype; //下载来源
            ViewBag.dbId = dbID;
            ViewBag.DbName = dbName;  //code
            ViewBag.DbDispName = dbinfo.DatabaseName;//数据库名
            ViewBag.recordId = int.Parse(sysID);
            ViewBag.Type = mediaType;
            IList<SearchQuery> searchQuery = new List<SearchQuery>();
            searchQuery.Add(new SearchQuery("SYS_FLD_SYSID", sysID));
            DataSet ds = searchService.SearchDetail(dbID, searchQuery);
            ViewBag.DetialField = null;
            string title = "";
            if (ds != null && ds.Tables.Count > 0)
            {
                ViewBag.DetialField = ds.Tables[0];
                ViewBag.RColumnInfo = ds.Tables["ColumnInfo"];
                if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Columns.Count > 0 && ds.Tables[0].Rows[0][0] != null)
                {
                    title = ds.Tables[0].Rows[0][0].ToString();
                }
                //获取对应的文件信息 过滤文件类型
                IList<METADATA_FILE> listfile = searchService.GetFile(int.Parse(sysID), dbName, (MediaType)mediaType);
                ViewBag.FileInfo = listfile;
                ViewBag.FileCountView = listfile == null ? 0 : listfile.Count;


                //下载，不过滤文件类型
                IList<METADATA_FILE> listfileAll = searchService.GetFile(int.Parse(sysID), dbName);
                ViewBag.FileInfoAll = listfileAll;
                ViewBag.FileCount = listfileAll == null ? 0 : listfileAll.Count;


                //图片
                ViewBag.Pic = ResourceHelper.GetFirstSmallPicURL(Convert.ToInt32(dbID), Convert.ToInt32(sysID));
                if (mediaType == (int)MediaType.Audio)
                {
                    //获取第一条数据下载
                    ViewBag.Down = ResourceHelper.GetFileDownloadURLByRecoredId(Convert.ToInt32(dbID), Convert.ToInt32(sysID), downtype);
                    //播放
                    ViewBag.PlayStream = ResourceHelper.GetFirstStreamURL(Convert.ToInt32(dbID), Convert.ToInt32(sysID), MediaType.Audio);
                    //文件名称
                    if (listfile != null && listfile.Count > 0)
                    {
                        ViewBag.PlayStreamName = listfile[0].FILENAME;
                    }
                }
                else if (mediaType == (int)MediaType.Video)
                {
                    //获取第一条数据下载
                    ViewBag.Down = ResourceHelper.GetFileDownloadURLByRecoredId(Convert.ToInt32(dbID), Convert.ToInt32(sysID), downtype);
                    //播放
                    ViewBag.PlayStream = ResourceHelper.GetFirstStreamURL(Convert.ToInt32(dbID), Convert.ToInt32(sysID), MediaType.Video);
                }
                else if (mediaType == (int)MediaType.Doc)
                {
                    //下载
                    ViewBag.Down = ResourceHelper.GetFileDownloadURLByRecoredId(Convert.ToInt32(dbID), Convert.ToInt32(sysID), downtype);
                    if (listfile != null && listfile.Count > 0)//
                    {
                        ViewBag.LookOnline = Url.Action("DocView", "DocResource", new { dbName = dbName, resourceId = listfile[0].SYSID, recordId = sysID, dbId = dbID, downType = downtype });
                        ViewBag.ViewOnlineFileID = listfile[0].SYSID;
                        //只有一个文件时用
                    }
                    else
                    {
                        ViewBag.LookOnline = "";
                    }

                }
                else if (mediaType == (int)MediaType.Pic)
                {
                    //下载
                    ViewBag.Down = ResourceHelper.GetFileDownloadURLByRecoredId(Convert.ToInt32(dbID), Convert.ToInt32(sysID), downtype);
                }
                else
                {
                    //下载
                    ViewBag.Down = ResourceHelper.GetFileDownloadURLByRecoredId(Convert.ToInt32(dbID), Convert.ToInt32(sysID), downtype);
                    if (listfile != null && listfile.Count > 0)//
                    {
                        ViewBag.LookOnline = Url.Action("DocView", "DocResource", new { dbName = dbName, resourceId = listfile[0].SYSID, recordId = sysID, dbId = dbID, downType = downtype });
                        ViewBag.ViewOnlineFileID = listfile[0].SYSID;
                        //只有一个文件时用
                    }
                    else
                    {
                        ViewBag.LookOnline = "";
                    }
                }

            }

            title = StringHelper.UnDealInfo(title);
            title = ColumnAliasHelper.UnChangeStr(title);
            ViewBag.recTitle = title;
            LogOpr.Browse(dbID.ToString(), dbName, sysID, browsetype, title);//记录浏览次数

            //收藏数据
            DataTable dtfav = centerService.GetFavFolderList(dbName);
            if (dtfav != null && dtfav.Rows.Count > 0)
            {
                int m = 0;
                foreach (DataRow dr in dtfav.Rows)
                {
                    if (sysID == dr["RecordID"].ToString())
                    {
                        m = 1;
                        break;
                    }
                }
                ViewBag.IsFav = m;
            }
            return View();

        }
        public ActionResult FileList()
        {
            return View();
        }


        public ActionResult DataList(int dbId, int recordId, string similarWord, string type, string dbCode)
        {
            //if (String.IsNullOrEmpty(similarWord))
            //{
            //    return new ContentResult();
            //}
            int num = 4;//如果配置文件没有配置该节点，则默认取4条记录
            if (ConfigHelper.GetAppSettingsValue("similarSum") != "")
            {
                num = int.Parse(ConfigHelper.GetAppSettingsValue("similarSum"));
            }
            string videoLibID = ConfigHelper.GetAppSettingsValue("VideoLibID");
            string picLibID = ConfigHelper.GetAppSettingsValue("PicLibID");
            string audioLibID = ConfigHelper.GetAppSettingsValue("AudioLibID");
            string eBookLibID = ConfigHelper.GetAppSettingsValue("EBookLibID");
            DataTable similarList = searchService.GetSimilarList(dbCode);
            List<SYS_CMS_DATABASE> listResult = new List<SYS_CMS_DATABASE>();
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>();
            string keyField = "";
            if (similarList != null && similarList.Rows.Count > 0)
            {
                string field = ParserField(similarList);
                DataSet docInfo = searchService.SingleSearch(dbId, dbCode, new List<SearchQuery> { new SearchQuery("SYS_FLD_SYSID", recordId.ToString()) }, 0, null, null, null, 1, 1, field);
                foreach (DataRow dr in similarList.Rows)
                {
                    DataSet ds = null;
                    if ((int)dr["SysID"] == dbId)
                    {
                        ds = searchService.SingleSearch((int)dr["SysID"], (string)dr["DatabaseCode"], new List<SearchQuery> {
                        new SearchQuery((string)dr["RelationField"], docInfo.Tables[0].Rows[0][(string)dr["DBField"]].ToString()),
                        new SearchQuery("SYS_FLD_SYSID", recordId.ToString(), ConditionType.Ne, SearchMatchType.And) }, 0, null, null, null, 1, num);
                    }
                    else
                    {
                        switch ((SearchType)(int)dr["SearchType"])
                        {
                            case SearchType.CNKI:
                                keyField = ConfigHelper.GetCNKIResourceKey();
                                break;
                            case SearchType.KSPIRDER:
                                keyField = ConfigHelper.GetKspiderKey();
                                break;
                            case SearchType.TPI:
                                keyField = "SYS_FLD_SYSID";
                                break;
                            default:
                                keyField = "SYS_FLD_SYSID";
                                break;
                        }
                        ds = searchService.SingleSearch((int)dr["SysID"], (string)dr["DatabaseCode"], new List<SearchQuery> { new SearchQuery((string)dr["RelationField"], docInfo.Tables[0].Rows[0][(string)dr["DBField"]].ToString()), new SearchQuery(keyField, "-12345", ConditionType.Ne, SearchMatchType.And) }, 0, null, null, null, 1, num);
                    }
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        //转换类型
                        int dtype = 0;
                        if (videoLibID.Equals(dr["TemplateID"].ToString()))
                        {
                            dtype = (int)MediaType.Video;
                        }
                        else if (picLibID.Equals(dr["TemplateID"].ToString()))
                        {
                            dtype = (int)MediaType.Pic;
                        }
                        else if (audioLibID.Equals(dr["TemplateID"].ToString()))
                        {
                            dtype = (int)MediaType.Audio;
                        }
                        else if (eBookLibID.Equals(dr["TemplateID"].ToString()))
                        {
                            dtype = (int)MediaType.Ebook;
                        }
                        else
                        {
                            dtype = 0;
                        }
                        dr["TemplateID"] = dtype;
                        listResult.Add(new SYS_CMS_DATABASE() { SysID = (int)dr["SysID"], DatabaseCode = (string)dr["DatabaseCode"], TemplateID = (int)dr["TemplateID"], DatabaseName = (string)dr["DatabaseName"] });
                        dicList.Add((string)dr["DatabaseCode"], ds.Tables[0]);
                    }
                }
            }

            //统计有几种类型的相关数据
            List<int> listTitle = new List<int>();
            foreach (SYS_CMS_DATABASE dbcate in listResult)
            {
                if (!listTitle.Contains(dbcate.TemplateID))
                {
                    listTitle.Add(dbcate.TemplateID);
                }
            }
            ViewBag.TitleType = listTitle;
            //ViewBag.Type = type;
            ViewBag.DbList = listResult;
            ViewBag.TableList = dicList;
            return PartialView("DataList");
        }

        private string ParserField(DataTable similarList)
        {
            IList<string> fieldList = new List<string>();
            foreach (DataRow dr in similarList.Rows)
            {
                if (!fieldList.Contains((string)dr["DBField"]))
                {
                    fieldList.Add((string)dr["DBField"]);
                }
            }
            string field = string.Join(",", fieldList);
            return field;
        }

        /// <summary>
        /// 获取音频视频的url
        /// </summary>
        /// <param name="flage"> 0 音频播放  1 视频播放</param>
        /// <returns></returns>
        public string GetStreamUrl(int dbID, int sysID, int flage)
        {
            string url = "";
            //首先判断文件是否存在，是否被支持
            string filePath = fileService.GetDigitalFile(dbID, sysID);

            string str = "";
            if (flage == 0)
            {
                str = fileService.ParseFile(MediaType.Audio, filePath);
            }
            else
            {
                str = fileService.ParseFile(MediaType.Video, filePath);
            }
            if (str == "1")//支持该文件并且该文件存在则获取该文件路径
            {
                if (0 == flage)
                {
                    url = ResourceHelper.GetAudioStreamURL(Convert.ToInt32(dbID), Convert.ToInt32(sysID));
                }
                else
                {
                    url = ResourceHelper.GetVideoStreamURL(Convert.ToInt32(dbID), Convert.ToInt32(sysID));
                }
            }
            else
            { url = str; }
            return url;
        }
    }
}
